package com.wens.baselibrary.util.bitmap.mosaic

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import kotlin.math.ceil

object MosaicUtil {
    fun getGridMosaic(bmBaseLayer: Bitmap, mGridWidth: Int): Bitmap {
        val mImageWidth = bmBaseLayer.width
        val mImageHeight = bmBaseLayer.height
        val bitmap = Bitmap.createBitmap(
            mImageWidth, mImageHeight,
            Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(bitmap)
        val horCount = ceil((mImageWidth / mGridWidth.toFloat()).toDouble()).toInt()
        val verCount = ceil((mImageHeight / mGridWidth.toFloat()).toDouble()).toInt()
        val paint = Paint()
        paint.isAntiAlias = true
        for (horIndex in 0 until horCount) {
            for (verIndex in 0 until verCount) {
                val l = mGridWidth * horIndex
                val t = mGridWidth * verIndex
                var r = l + mGridWidth
                if (r > mImageWidth) {
                    r = mImageWidth
                }
                var b = t + mGridWidth
                if (b > mImageHeight) {
                    b = mImageHeight
                }
                val color = bmBaseLayer.getPixel(l, t)
                val rect = Rect(l, t, r, b)
                paint.color = color
                canvas.drawRect(rect, paint)
            }
        }
        canvas.save()
        return bitmap
    }
}
